package com.abhimanyu.service;

import java.util.ArrayList;
import java.util.List;

import com.abhimanyu.service.model.DollarRateServiceData;

public class XoomDollarRateObserver extends AbstractDollarRateObserver {

	private static final String PARSE_START = "1 USD = ";
	private static final String PARSE_END = "INR";

	public XoomDollarRateObserver() {
		String url = "https://www.xoom.com/india";
		super.setUrl(url);
	}

	public List<DollarRateServiceData> getCurrentDollarRate() {
		List<DollarRateServiceData> serviceModelList = new ArrayList<DollarRateServiceData>();
		DollarRateServiceData serviceModel = new DollarRateServiceData();
		String dollarRate = null;
		try {
			String webPageContent = executeDollarService();
			dollarRate = getDollarRate(webPageContent);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		serviceModel.setDollarRateData(dollarRate);
		serviceModel.setServiceName(toString());
		serviceModelList.add(serviceModel);
		return serviceModelList;
	}

	/*
	 * // HTTP GET request private String getXoomWebPageForDollarRate() throws
	 * Exception {
	 * 
	 * URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection)
	 * obj.openConnection();
	 * 
	 * // optional default is GET con.setRequestMethod("GET");
	 * con.setReadTimeout(0); // add request header //
	 * con.setRequestProperty("User-Agent", USER_AGENT);
	 * 
	 * int responseCode = con.getResponseCode();
	 * System.out.println("\nSending 'GET' request to URL : " + url);
	 * System.out.println("Response Code : " + responseCode);
	 * 
	 * BufferedReader in = new BufferedReader(new InputStreamReader(
	 * con.getInputStream())); String inputLine; StringBuffer response = new
	 * StringBuffer();
	 * 
	 * while ((inputLine = in.readLine()) != null) { response.append(inputLine);
	 * } in.close();
	 * 
	 * // print result System.out.println(response.toString());
	 * 
	 * return response.toString(); }
	 */

	private String getDollarRate(String webPageContent) {
		return webPageContent.substring(webPageContent.indexOf(PARSE_START)
				+ PARSE_START.length(), webPageContent.indexOf(PARSE_END));
	}

	public static void main(String[] args) {
		System.out.println(new XoomDollarRateObserver().getCurrentDollarRate());
	}

	@Override
	public String toString() {
		return "Xoom";
	}
}
